namespace RBAC.Read.Api.Application.Handler.QualityHandler
{
    using MediatR;
    using Microsoft.Extensions.Logging;
    using RBAC.Domain.QualityManage;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue.Base;
    using RBAC.Read.Api.Application.Command.QualityCommand;
    using RBAC.Read.Api.Application.Dto.Quality;

    /// <summary>
    /// 按 Id 获取质量工单详情 处理器。
    /// </summary>
    /// <remarks>
    /// 主要逻辑：
    /// 1. 校验 <c>Id</c> > 0。
    /// 2. 查询未删除（<c>IsDeleted = 0</c>）的工单实体。
    /// 3. 映射为 <see cref="QualityOrderDetailDto"/> 返回。
    /// 4. 统一取消与异常处理。
    /// </remarks>
    /// </summary>
    public class GetQualityOrderDetailByIdHandler : IRequestHandler<GetQualityOrderDetailByIdCommand, APIResult<QualityOrderDetailDto>>
    {
        private readonly IBaseRepository<QualityOrder> _orderRepo;
        private readonly ILogger<GetQualityOrderDetailByIdHandler> _logger;

        public GetQualityOrderDetailByIdHandler(IBaseRepository<QualityOrder> orderRepo, ILogger<GetQualityOrderDetailByIdHandler> logger)
        {
            _orderRepo = orderRepo;
            _logger = logger;
        }

        /// <summary>
        /// 处理“按 Id 获取质量工单详情”请求。
        /// </summary>
        /// <param name="request">包含工单 Id 的查询命令。</param>
        /// <param name="cancellationToken">取消令牌。</param>
        /// <returns>返回 <see cref="APIResult{T}"/>，<c>Code</c> 表示成功/失败，<c>Data</c> 为详情数据。</returns>
        public Task<APIResult<QualityOrderDetailDto>> Handle(GetQualityOrderDetailByIdCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<QualityOrderDetailDto>();
            try
            {
                // 检查是否被取消
                cancellationToken.ThrowIfCancellationRequested();
                // 参数校验：Id 必须有效
                if (request.Id <= 0)
                {
                    return Task.FromResult(new APIResult<QualityOrderDetailDto> { Code = APIEnums.Fail, Msg = "Id无效", Data = null! });
                }

                // 查询未删除的目标实体
                var entity = _orderRepo.GetFirstOrDefault("Id = @Id AND IsDeleted = 0", new { Id = request.Id });
                if (entity == null)
                {
                    return Task.FromResult(new APIResult<QualityOrderDetailDto> { Code = APIEnums.Fail, Msg = "未找到质量工单", Data = null! });
                }

                // 实体映射到详情 DTO
                var dto = new QualityOrderDetailDto
                {
                    Id = entity.Id,
                    OrderNo = entity.OrderNo,
                    Title = entity.Title,
                    SourceWorkOrderNo = entity.SourceWorkOrderNo,
                    ProductId = entity.ProductId,
                    ProductName = entity.ProductName,
                    OwnerUserId = entity.OwnerUserId,
                    OwnerUserName = entity.OwnerUserName,
                    ProcessCount = entity.ProcessCount,
                    ReportCount = entity.ReportCount,
                    Status = entity.Status,
                    Remark = entity.Remark
                };

                // 设置返回结果
                result.Code = APIEnums.Success;
                result.Data = dto;
                result.Msg = "获取质量工单详情成功";
            }
            catch (OperationCanceledException)
            {
                // 捕获取消异常
                _logger.LogWarning("获取质量工单详情被取消");
                result.Code = APIEnums.Error;
                result.Msg = "请求已取消";
                result.Data = null!;
            }
            catch (Exception ex)
            {
                // 统一异常处理与日志
                _logger.LogError(ex, "获取质量工单详情失败: {Message}", ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = "获取质量工单详情失败";
                result.Data = null!;
            }

            return Task.FromResult(result);
        }
    }
}
